package com.tanhua.server.controller;

import com.itheima.commons.util.JwtUtils;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.server.service.UserInfoService;
import com.tanhua.server.service.UserService;
import io.jsonwebtoken.Claims;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;
@Slf4j
@RestController
@RequestMapping("/user")
public class LoginController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserInfoService userInfoService;

    /**
     *用户登录，发送短信验证
     * @param map
     */
    @PostMapping("/login")
    public ResponseEntity login(@RequestBody Map map){
        //获取手机号
        String phone = (String) map.get("phone");
        //调用userService发送短信
        userService.sendCode(phone);
        return ResponseEntity.ok(null);

    }

    @PostMapping("/loginVerification")
    public ResponseEntity loginVerification(@RequestBody Map map){
        log.info("接收过来的参数为:{}",map);
        //获取手机号和验证码
        String phone = (String) map.get("phone");
        String verificationCode = (String) map.get("verificationCode");
        Map retMap = userService.loginVerification(phone,verificationCode);
        return ResponseEntity.ok(retMap);
    }

    /**
     * 保存用户信息
     * UserInfo
     * 请求体中携带token
     *
     */
    @PostMapping("/loginReginfo")
    public ResponseEntity loginReginfo(@RequestBody UserInfo userInfo,
                                       @RequestHeader("Authorization") String token){
        //1.判断token是否合法
//        boolean b = JwtUtils.verifyToken(token);
//        if (!b){
//            return ResponseEntity.status(401).body(null);
//        }

        //2.向userinfo中设置ID
        //通过线程获取ID
        Long id = UserHolder.getUserId();
        userInfo.setId(id);
        //3.调用service保存数据
        userInfoService.save(userInfo);
        return ResponseEntity.ok(null);
    }
    /**
     *上传用户头像
     */
    @PostMapping("/loginReginfo/head")
    public ResponseEntity head(MultipartFile headPhoto, @RequestHeader("Authorization") String token) throws IOException {

        //1.判断token是否合法
//        boolean b = JwtUtils.verifyToken(token);
//        if (!b){
//            return ResponseEntity.status(401).body(null);
//        }
        //2、向userinfo中设置用户id
//        Claims claims = JwtUtils.getClaims(token);
//        Integer id = (Integer) claims.get("id");
        Long id = UserHolder.getUserId();
        //3、调用service
        userInfoService.updateHead(headPhoto,id);
        return ResponseEntity.ok(null);
    }
}
